<template>
  <div>
      <s-container @reset="handleQueryReset" @search="handleQuery" :loading="loading">
        <template #searchForm>
            <n-form ref="searchRef" :label-width="80" :model="searchForm.value" label-placement="left" inline>
                <n-form-item label="名字" path="name" class="fi-w">
                  <n-input v-model:value="searchForm.value.name" @keyup.enter.native="handleQuery" clearable/>
                </n-form-item>
                <n-form-item label="分组" path="configGroup" class="fi-w">
                  <n-input v-model:value="searchForm.value.configGroup" @keyup.enter.native="handleQuery" clearable/>
                </n-form-item>
            </n-form>
        </template>
        <template #btnBar>
          <s-bar-add-btn @click="handleAddClick" v-permission="['sys:config:add']"></s-bar-add-btn>
          <s-bar-del-btn :disabled="!(checkRows && checkRows.length>0)" :click="handleDeleteListPositive" v-permission="['sys:config:remove']"></s-bar-del-btn>
          <TableColumnSetting v-model:columns="columns" />
    </template>
        <template #toolBar></template>
        <template #dataTable>
          <s-data-table :list="list" v-model:pageObj="pageObj" :columns="columns" :loading="loading"
                              :checked-row-keys="checkRows.map(it=>it.id)" @update:checked-row-keys="handleCheck"/>
        </template>
    </s-container>
    <slef-form  v-model:visible="showModal" :operate-type="editKey == null?'add' : 'edit'" :editKey="editKey" @submitted="handleSubmitted"></slef-form>
  </div>
</template>

<script setup lang='tsx'>
	import {h, ref, onMounted, Ref} from 'vue';
	import {DataTableColumns, NSpace, FormInst} from 'naive-ui';
	import {usePageList} from '@/hooks';
	import {
			fetchConfigPage,
			fetchDelConfig
	} from '@/service/api/sys/config'
	import TooltipBtn from "@/components/custom/tooltip-btn.vue"
	import TablePopconfirmBtn from "@/components/custom/table-popconfirm-btn.vue"
	import slefForm from "./form.vue"
	import {Config,typeOptions} from "./index"

	interface DataSource extends Config {
	}

	interface SearchForm{
      name?:string;
      group?:string;
      type?:string;
      remark?:string;
	}

	const columns: Ref<DataTableColumns<DataSource>> = ref([
			{
					type: "selection"
			},
			{
					title: '名字',
					key: 'name',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: '配置',
					key: 'value',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: '分组',
					key: 'configGroup',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: '类型',
					key: 'type',
					align: 'center',
					ellipsis: {
							tooltip: true
					},
          render(rowData: DataSource){
            const type = rowData.type
            const typeStr = typeOptions.find(it=>it.value === type)?.label
            return <> {typeStr} </>
          }
			},
			{
					title: '备注',
					key: 'remark',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: '创建',
					key: 'createBy',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: '更新',
					key: 'updateBy',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: '创建时间',
					key: 'createTime',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: '更新时间',
					key: 'updateTime',
					align: 'center',
					ellipsis: {
							tooltip: true
					}
			},
			{
					title: "操作列",
					key: "",
					align: 'center',
					width: 200,
					fixed: 'right',
					render(rowData: DataSource) {
							return [
									h(NSpace, {justify: "center"}, [
											h(TooltipBtn, {
													str: "编辑", type: "success",permission: "['sys:config:edit']", onClick: () => {
															handleEditClick(rowData)
													}
											}),
											h(TablePopconfirmBtn, {
													confirmText: "是否确认删除当前内容", permission: "['sys:config:remove']",onPositiveClick: () => {
															return handleDeletePositive(rowData)
													}
											})
									])

							]
					}
			}
	]);
	const searchRef = ref<FormInst | null>(null)
	const checkRows = ref<DataSource[]>([]);

	const showModal = ref(false);
  const editKey = ref<Common.IdType | null>(null)


	const {
	loading,
	searchForm,
	list,
	pageObj,
	getList,
	handleQueryReset,
	handleQuery
 } = usePageList<DataSource>(
	initSearchFormData,
	fetchConfigPage,
	()=>{
		checkRows.value=[]
	},
	undefined
);


	function initSearchFormData(): SearchForm {
			return {}
	}



function handleCheck(keys: Array<string | number>, rows: DataSource[]) {
    checkRows.value = rows
}



	async function handleDeletePositive(row: DataSource) {
			if (!row || !row.id) {
					window.$message?.error('当前行数据异常,请刷新后重试');
					return;
			}
			const delArr = [];
			delArr.push(row.id);
			await fetchDelConfig(delArr);
			await getList();
	}

	async function handleDeleteListPositive() {
			await fetchDelConfig(checkRows?.value.map(it => it.id!))
			getList()
			return true;
	}
  function handleEditClick(row: DataSource) {
    if(!row || !row.id){
        window.$message?.error("当前行数据异常,请刷新后重试")
        return;
    }
    editKey.value = row.id
    showModal.value = true;
  }
  function handleAddClick(){
    showModal.value = true;
  }
  function handleSubmitted(){
      editKey.value = null
      getList()
  }
	onMounted(() => {
			getList()
	})
</script>

<style lang='scss' scoped>

</style>
